var util        = require("util");
var md5         = require("md5") ;
var UUID        = require('node-uuid');
var express     = require('express');
var url         = require("url");
var router      = express.Router();

//动态资源引用
var tools          = require("./../utils/tools.js");
var su          = require("./../utils/dbConnect.js");
var Cache       = require("./../utils/redisConnect.js");




/**
 * @api {get} /index/queryLogList log获取列表
 * @apiDescription log获取列表
 * @apiName queryLogList
 * @apiGroup Log
 * @apiSuccessExample {json} Success-Response:
 *    {
 *        "id": 1,
 *        "updatetime": "2019-05-06T01:58:56.000Z",
 *        "createtime": "2019-05-06T01:58:59.000Z",
 *        "count": 6
 *    }
 * @apiSampleRequest http://127.0.0.1:8080/index/queryLogList
 * @apiVersion 1.0.0
 */
router.get('/queryLogList', function(req, res, next) {
    console.log("-------test--------"+req);
    var userId = 1;
    var user1 = '{"id": 1,"updatetime": "2019-05-06T01:58:56.000Z"}'
    // Cache.del("user_1");
    return Cache.get("user_" + userId).then(function(user){
        console.log("-------redisConnect--------"+user);
        if(user){
          res.send(JSON.stringify(user1));
        }else{
          //获取参数
          var url_args = url.parse(req.url, true).query;
          var sql = " SELECT * FROM logcount ";
          sql = util.format(sql);
          su.sql_allquery(sql, function(result){
              //写入缓存 设置4s的有效期，即生命周期,过了4S之后，就会没掉。 set('key',value)
              Cache.set("user_"+ result[0].id,result,5);
              console.log("-------result--------"+result);
              res.send(JSON.stringify(result));
          });
        }
    });
});

/**
 * @api {post} /index/installLog 新增Log
 * @apiDescription 新增Log
 * @apiName installLog
 * @apiGroup Log
 * @apiParam {string} remote_addr 请求地址
 * @apiParam {string} api_type 请求类型
 * @apiSuccess {json} resp_result
 * @apiSuccessExample {json} Success-Response:
 *    {
          "code": 0,
          "msg": "Insert successfully OK"
      }
 * @apiSampleRequest http://127.0.0.1:8080/index/installLog
 * @apiVersion 1.0.0
 */
router.post('/installLog', function(req, res, next) {
    //获取参数
    // var url_args = url.parse(req.url, true).query;
    var url_args = req.body;
    console.log("-------url_args--------"+url_args.remote_addr);
    if (url_args == null) {
        res.send(JSON.stringify({code: -1, msg: "you must give me 'remote_addr/api_type' arg for query."}));
        return;
    }
    var sql = " INSERT INTO logcount (remote_addr,api_type,req_day) VALUES ('%s','%s','%s'); ";
    sql = util.format(sql,url_args.remote_addr,url_args.api_type,tools.getFormatDate('day'));
    var resp_result = {};
    su.sql_allquery(sql, function(result){
        console.log("-------插入结束--------"+result);
        resp_result.code = 0;
        resp_result.msg = "Insert successfully OK";
        res.send(JSON.stringify(resp_result));
    });
});












module.exports = router;
